package org.rmm.service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.rmm.db.Repository;
import org.rmm.model.Order;
import org.rmm.representation.OrderRepresentation;

/**
 * /GetOrderDetails
 * @author jvelilla
 */

public class GetOrderDetailsManagementService extends HttpServlet {

	private static final String APPLICATION_JSON = "application/json";
	private static final String APPLICATION_XML = "application/xml";
	
	private static final Logger LOG = Logger
			.getLogger(GetOrderDetailsManagementService.class);
	private static final long serialVersionUID = 1L;

	
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		try {
			BufferedReader requestReader = req.getReader();
			String orderRequest = extractOrder(requestReader);
			LOG.info("Order body [ +" + orderRequest + " ]");
			processGetOrderDetails(orderRequest, resp);
		}catch (Exception e) {
			resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
		}
		 finally {
		}
	 }



	private void processGetOrderDetails(String orderRequest, HttpServletResponse resp) throws IOException {
		LOG.info("Start processGetOrderDetails");
		Order order = new OrderRepresentation().fromXML(orderRequest);
		resp.setContentType(APPLICATION_XML);
		PrintWriter out = resp.getWriter();
		Order retrieveOrder = Repository.INSTANCE.retrieveOrder(order.getId());
		if (retrieveOrder != null) {
			out.print(new OrderRepresentation().asXML(retrieveOrder));
			resp.setStatus(HttpServletResponse.SC_OK);
		} else {
			resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
		}
	}



	private String extractOrder(BufferedReader requestReader) throws IOException {
		 StringBuffer result = new StringBuffer();
		  String line = null;
		    while ((line = requestReader.readLine()) != null){
		      result.append(line);
		    }
		 return result.toString();   
		 
	}
	
}
